package com.abocode.smarten.com.abocode.smarten.client;

import com.abocode.smarten.com.abocode.smarten.client.event.ConfigurationListener;
import org.springframework.beans.factory.FactoryBean;
import java.util.List;
import java.util.Properties;

/**
 * Description:
 * Define a  {@code ClientPropertiesFactoryBean} implementations {@link FactoryBean}.
 *
 * @author: guanxianfei
 * @date: 2019/7/24
 */
public class ClientPropertiesFactoryBean implements FactoryBean<Properties> {
    private static ClientProperties clientProperties;

    private static boolean init = false;

    public ClientPropertiesFactoryBean() {
        this(null);
    }

    public ClientPropertiesFactoryBean(List<ConfigurationListener> listeners) {
        init = true;
        clientProperties = new ClientProperties();
        if(listeners != null) {
            for(ConfigurationListener listener : listeners) {
                clientProperties.addConfigurationListener(listener);
            }
        }
    }

    public ClientPropertiesFactoryBean(final String projectCode, final String profile, final String moduleCodes) {
        this(projectCode, profile, moduleCodes, null);
    }

    public ClientPropertiesFactoryBean(final String projectCode, final String profile, final String moduleCodes, List<ConfigurationListener> listeners) {
        init = true;
        clientProperties = new ClientProperties(projectCode, profile);
        if(listeners != null) {
            for(ConfigurationListener listener : listeners) {
                clientProperties.addConfigurationListener(listener);
            }
        }
    }

    public ClientPropertiesFactoryBean(String host, int port, final String projectCode, final String profile, final String moduleCodes) {
        this(host, port, projectCode, profile, moduleCodes, null);
    }

    public ClientPropertiesFactoryBean(String host, int port, final String projectCode, final String profile, final String moduleCodes, List<ConfigurationListener> listeners) {
        init = true;
        clientProperties = new ClientProperties(host, port, projectCode, profile, moduleCodes);

        if(listeners != null) {
            for(ConfigurationListener listener : listeners) {
                clientProperties.addConfigurationListener(listener);
            }
        }
    }

    public Properties getObject() throws Exception {
        return clientProperties.getProperties();
    }

    public Class<?> getObjectType() {
        return Properties.class;
    }

    public boolean isSingleton() {
        return true;
    }

    public static ClientProperties getClientProperties() {
        if(!init) {
            throw new RuntimeException("ClientPropertiesFactoryBean 没有初始化");
        }
        return clientProperties;
    }
}
